package com.cwj.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Chenwujie
 * @date: 2021-05-13 08:47
 */
public class RSATest {
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {

        SignatureAlgorithm algorithm = SignatureAlgorithm.PS512;
        KeyPair keyPair =
            Keys.keyPairFor(algorithm);
        PrivateKey aPrivate = keyPair.getPrivate();
        PublicKey aPublic = keyPair.getPublic();
        System.out.println("aPrivate: " + Base64.getEncoder().encodeToString(aPrivate.getEncoded()));
        System.out.println("aPublic: " + Base64.getEncoder().encodeToString(aPublic.getEncoded()));
        PrivateKey key1 = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(aPrivate.getEncoded()));
        PublicKey key2 = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(aPublic.getEncoded()));

        Map<String, String> claims = new HashMap<>();
        claims.put("username", "cwj");
        String compact = Jwts.builder().signWith(key1, algorithm).setClaims(claims).compact();
        System.out.println("token: "+ compact);

        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key2).build().parseClaimsJws(compact);
        System.out.println("stringJws.body: " + claimsJws.getBody());
    }
}
